<template>
  <div class="task-manage">
    <el-card shadow="never">
      <div slot="header" class="card-header">
        <span>任务管理</span>
        <el-button type="primary" icon="el-icon-plus" size="small" @click="handleAdd">
          添加任务
        </el-button>
      </div>

      <!-- 查询表单 -->
      <el-form :inline="true" :model="queryForm" size="small" class="query-form">
        <el-form-item label="任务名称">
          <el-input v-model="queryForm.taskName" placeholder="请输入任务名称" clearable/>
        </el-form-item>
        <el-form-item label="企业名称">
          <el-input v-model="queryForm.companyName" placeholder="请输入企业名称" clearable/>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryForm.status" placeholder="请选择状态" clearable>
            <el-option label="禁用" :value="0"/>
            <el-option label="启用" :value="1"/>
            <el-option label="运行中" :value="2"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
          <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格 -->
      <el-table :data="tableData" border style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="60"/>
        <el-table-column prop="taskName" label="任务名称" width="380"/>
        <el-table-column prop="companyName" label="企业名称" width="280"/>
        <el-table-column prop="companyTaxNo" label="企业税号" width="180"/>
        <!-- <el-table-column prop="entryId" label="报关单号" width="120"/> -->
        <el-table-column prop="declareDateRange" label="查询范围" width="100">
          <template slot-scope="scope">
            前{{ scope.row.declareDateRange }}天
          </template>
        </el-table-column>
        <el-table-column prop="cronExpression" label="Cron表达式" width="210"/>
        <el-table-column prop="status" label="状态" width="80">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status === 0" type="info" size="small">禁用</el-tag>
            <el-tag v-else-if="scope.row.status === 1" type="success" size="small">启用</el-tag>
            <el-tag v-else type="warning" size="small">运行中</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastExecuteTime" label="最后执行时间" width="180">
          <template slot-scope="scope">
            {{ scope.row.lastExecuteTime | formatDate }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button 
              size="mini" 
              type="text" 
              v-if="scope.row.status === 0"
              @click="handleToggleStatus(scope.row, 1)">
              启用
            </el-button>
            <el-button 
              size="mini" 
              type="text" 
              v-if="scope.row.status === 1"
              @click="handleToggleStatus(scope.row, 0)">
              禁用
            </el-button>
            <el-button 
              size="mini" 
              type="text" 
              v-if="scope.row.status === 1"
              @click="handleExecute(scope.row)">
              执行
            </el-button>
            <el-button size="mini" type="text" style="color: #f56c6c" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryForm.current"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="queryForm.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog 
      :title="dialogTitle" 
      :visible.sync="dialogVisible" 
      width="600px"
      @close="handleDialogClose">
      <el-form :model="form" :rules="rules" ref="form" label-width="120px" size="small">
        <el-form-item label="任务名称">
          <el-input v-model="form.taskName" placeholder="自动生成" disabled/>
          <div class="form-tip">根据企业名称和日期自动生成</div>
        </el-form-item>
        <el-form-item label="企业名称" prop="companyName">
          <el-input v-model="form.companyName" placeholder="请输入企业名称" @input="generateTaskName"/>
        </el-form-item>
        <el-form-item label="企业税号"  prop="companyTaxNo">
          <el-input v-model="form.companyTaxNo" placeholder="请输入企业税号"/>
        </el-form-item>
        <el-form-item label="报关单号">
          <el-input v-model="form.entryId" placeholder="请输入报关单号"/>
        </el-form-item>
        <el-form-item label="申报日期" prop="declareDateRange">
          <el-select v-model="form.declareDateRange" placeholder="请选择申报日期查询范围" style="width: 100%">
            <el-option label="前1天" :value="1"/>
            <el-option label="前5天" :value="5"/>
            <el-option label="前10天" :value="10"/>
            <el-option label="前15天" :value="15"/>
            <el-option label="前20天" :value="20"/>
            <el-option label="前30天" :value="30"/>
          </el-select>
          <div class="form-tip">从今天往前推N天的申报数据</div>
        </el-form-item>
        <el-form-item label="Cron表达式" prop="cronExpression">
          <el-row :gutter="10">
            <el-col :span="12">
              <el-select v-model="form.syncTimes" placeholder="同步频率" @change="generateCron" style="width: 100%">
                <el-option label="每天1次" :value="1"/>
                <el-option label="每天2次" :value="2"/>
                <el-option label="每天3次" :value="3"/>
                <el-option label="每天4次" :value="4"/>
                <el-option label="每天6次" :value="6"/>
              </el-select>
            </el-col>
            <el-col :span="12">
              <el-select v-model="form.startHour" placeholder="开始时间" @change="generateCron" :disabled="form.syncTimes === 0" style="width: 100%">
                <el-option v-for="h in 24" :key="h" :label="`${h-1}点`" :value="h-1"/>
              </el-select>
            </el-col>
          </el-row>
          <div class="form-tip">生成: {{ form.cronExpression || '请选择同步频率' }}</div>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="0">禁用</el-radio>
            <el-radio :label="1">启用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="warning" @click="handleSaveAndExecute" :loading="submitLoading" v-if="!isEdit">
          保存并立即执行
        </el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          {{ isEdit ? '保存' : '仅保存' }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getTaskList, createTask, updateTask, deleteTask, updateTaskStatus, executeTask } from '@/api/task'

export default {
  name: 'TaskManage',
  data() {
    return {
      loading: false,
      submitLoading: false,
      queryForm: {
        current: 1,
        size: 10,
        taskName: '',
        companyName: '',
        status: null
      },
      tableData: [],
      total: 0,
      dialogVisible: false,
      dialogTitle: '',
      isEdit: false,
      form: {
        id: null,
        taskName: '',
        companyName: '',
        companyTaxNo: '',
        entryId: '',
        declareDateRange: 1,
        cronExpression: '',
        syncTimes: 1,
        startHour: 2,
        status: 1,
        remark: ''
      },
      rules: {
        companyName: [{ required: true, message: '请输入企业名称', trigger: 'blur' }],
        companyTaxNo: [{ required: true, message: '请输入企业税号', trigger: 'blur' }],
        declareDateRange: [{ required: true, message: '请选择申报日期查询范围', trigger: 'change' }],
        cronExpression: [{ required: true, message: '请选择同步次数和开始时间', trigger: 'blur' }],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }]
      }
    }
  },
  filters: {
    formatDate(val) {
      if (!val) return '-'
      const date = new Date(val)
      return date.toLocaleString('zh-CN')
    }
  },
  mounted() {
    this.loadData()
  },
  methods: {
    loadData() {
      this.loading = true
      getTaskList(this.queryForm).then(res => {
        this.tableData = res.data.records
        this.total = res.data.total
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    handleQuery() {
      this.queryForm.current = 1
      this.loadData()
    },
    handleReset() {
      this.queryForm = {
        current: 1,
        size: 10,
        taskName: '',
        companyName: '',
        status: null
      }
      this.loadData()
    },
    handleSizeChange(val) {
      this.queryForm.size = val
      this.loadData()
    },
    handleCurrentChange(val) {
      this.queryForm.current = val
      this.loadData()
    },
    handleAdd() {
      this.isEdit = false
      this.dialogTitle = '添加任务'
      this.dialogVisible = true
      this.form = {
        id: null,
        taskName: '',
        companyName: '',
        companyTaxNo: '',
        entryId: '',
        declareDateRange: 1,
        cronExpression: '',
        syncTimes: 1,
        startHour: 2,
        status: 1,
        remark: ''
      }
      this.generateCron()
    },
    handleEdit(row) {
      this.isEdit = true
      this.dialogTitle = '编辑任务'
      this.dialogVisible = true
      this.form = { ...row }
      // 从 cron 表达式解析出同步次数和开始时间
      this.parseCron(row.cronExpression)
    },
    generateTaskName() {
      if (this.form.companyName) {
        const date = new Date()
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        this.form.taskName = `${this.form.companyName}_${year}${month}${day}`
      }
    },
    generateCron() {
      const times = this.form.syncTimes
      
      if (times === 0) {
        // 每5分钟执行一次
        this.form.cronExpression = '0 */5 * * * ?'
        return
      }
      
      if (times === null || times === undefined || this.form.startHour === null || this.form.startHour === undefined) {
        return
      }
      
      const startHour = this.form.startHour
      
      if (times === 1) {
        // 每天1次，在指定时间执行
        this.form.cronExpression = `0 0 ${startHour} * * ?`
      } else {
        // 每天多次，计算间隔小时数
        const interval = Math.floor(24 / times)
        const hours = []
        for (let i = 0; i < times; i++) {
          hours.push((startHour + i * interval) % 24)
        }
        this.form.cronExpression = `0 0 ${hours.join(',')} * * ?`
      }
    },
    parseCron(cronExpression) {
      if (!cronExpression) {
        this.form.syncTimes = 1
        this.form.startHour = 2
        return
      }
      
      try {
        // 检查是否是每5分钟的表达式: 0 */5 * * * ?
        if (cronExpression === '0 */5 * * * ?') {
          this.form.syncTimes = 0
          this.form.startHour = 0
          return
        }
        
        // 解析 Cron 表达式，格式: 0 0 2 * * ? 或 0 0 2,8,14,20 * * ?
        const parts = cronExpression.split(' ')
        if (parts.length >= 3) {
          const hoursPart = parts[2]
          const hours = hoursPart.split(',').map(h => parseInt(h))
          this.form.syncTimes = hours.length
          this.form.startHour = hours[0]
        }
      } catch (e) {
        this.form.syncTimes = 1
        this.form.startHour = 2
      }
    },
    handleDialogClose() {
      this.$refs.form.resetFields()
    },
    handleSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          // 自动生成任务名称
          this.generateTaskName()
          
          if (!this.form.taskName) {
            this.$message.warning('请输入企业名称')
            return
          }
          
          this.submitLoading = true
          const request = this.isEdit ? updateTask(this.form) : createTask(this.form)
          request.then(() => {
            this.$message.success(this.isEdit ? '更新成功' : '添加成功')
            this.dialogVisible = false
            this.loadData()
            this.submitLoading = false
          }).catch(() => {
            this.submitLoading = false
          })
        }
      })
    },
    handleSaveAndExecute() {
      this.$refs.form.validate(valid => {
        if (valid) {
          // 自动生成任务名称
          this.generateTaskName()
          
          if (!this.form.taskName) {
            this.$message.warning('请输入企业名称')
            return
          }
          
          this.submitLoading = true
          // 先创建任务
          createTask(this.form).then(res => {
            this.$message.success('任务创建成功')
            this.dialogVisible = false
            this.loadData()
            
            // 立即执行任务
            if (res.data && res.data.id) {
              executeTask(res.data.id).then(() => {
                this.$message.success('任务已触发执行')
                this.submitLoading = false
              }).catch(() => {
                this.$message.warning('任务已保存，但执行失败，请手动执行')
                this.submitLoading = false
              })
            } else {
              this.$message.warning('任务已保存，请手动执行')
              this.submitLoading = false
            }
          }).catch(() => {
            this.submitLoading = false
          })
        }
      })
    },
    handleToggleStatus(row, status) {
      const action = status === 1 ? '启用' : '禁用'
      this.$confirm(`确认${action}该任务？`, '提示', {
        type: 'warning'
      }).then(() => {
        updateTaskStatus(row.id, status).then(() => {
          this.$message.success(`${action}成功`)
          this.loadData()
        })
      })
    },
    handleExecute(row) {
      this.$confirm('确认立即执行该任务？', '提示', {
        type: 'warning'
      }).then(() => {
        executeTask(row.id).then(() => {
          this.$message.success('任务已触发执行')
        })
      })
    },
    handleDelete(row) {
      this.$confirm('确认删除该任务？', '提示', {
        type: 'warning'
      }).then(() => {
        deleteTask(row.id).then(() => {
          this.$message.success('删除成功')
          this.loadData()
        })
      })
    }
  }
}
</script>

<style scoped>
.task-manage {
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.query-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.form-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
}
</style>

